package com.longrise.android.byjk.plugins.poster.posterdetail.assist;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.PrintLog;

import java.lang.ref.SoftReference;
import java.util.HashMap;

/**
 * Created by godliness on 2017/10/27.
 * 海报详情页二维码
 */

public final class QrBitmap {

    private static final String TAG = "QrBitmap";

    private HashMap<String, SoftReference<Bitmap>> mMap;

    private QrBitmap() {
        mMap = new HashMap<>();
    }

    public static QrBitmap getInstance() {
        return Single.INSTANCE.getInstance();
    }

    private enum Single {

        INSTANCE;

        private QrBitmap mQrBitmap;

        Single() {
            mQrBitmap = new QrBitmap();
        }

        private QrBitmap getInstance() {
            return mQrBitmap;
        }
    }

    /**
     * 创建并获取二维码位图
     */
    public Bitmap createAndGetQrBitmap(Context context) {
        SoftReference<Bitmap> ref = mMap.get(TAG);
        Bitmap qrBitmap = null;
        if (ref != null) {
            qrBitmap = ref.get();
        }
        if (qrBitmap != null) {
            return qrBitmap;
        }
        return createQrBitmap(context);
    }

    public void clearBitmap() {
       if(mMap != null){
           mMap.clear();
       }
    }

    private void addBitmap(Bitmap bitmap) {
        SoftReference<Bitmap> ref = new SoftReference<>(bitmap);
        mMap.put(TAG, ref);
    }

    private Bitmap createQrBitmap(Context mContext) {
        Bitmap bitmap = null;
        try {
            String url = UserInfor.getInstance().getUrl();
            float width = ImageUtil.getImgWidth(mContext);
//            float width = ImageUtil.getDp(mContext, R.dimen.image);
            Bitmap qrBitmap = ImageUtil.generateBitmap(url, AppUtil.dip2px(width), AppUtil.dip2px(width));
            PrintLog.e(TAG, "createQrBitmap width dp = " + width + " width px = " + AppUtil.dip2px(width));
            Bitmap logoBitmap = UserInfor.getInstance().getBitmap();
            if (logoBitmap == null) {
                logoBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.default_pic);
            }
            bitmap = ImageUtil.addLogo(qrBitmap, logoBitmap);
            //将新生成的二维码图片添加到容器中
            addBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
